package org.budo.dubbo.protocol.http.page;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.dubbo.protocol.http.page.util.EntityStructureUtil;
import org.budo.support.lang.util.ReflectUtil;
import org.budo.support.spring.io.util.ResourceUtil;

import com.alibaba.dubbo.common.utils.CollectionUtils;

/**
 * @author lmw
 */
public class TypeStructurePage extends AbstractPage {
    private static final long serialVersionUID = 1058155021371573788L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        Class clazz = ReflectUtil.classForName(type);
        if (clazz.isEnum()) {
            this.renderEnumStructurePage(request, response);
        } else {
            this.renderTypeStructurePage(request, response);
        }
    }

    private void renderEnumStructurePage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter("type");
        Class clazz = ReflectUtil.classForName(type);

        List<String> enumNames = new ArrayList<String>();
        Object[] enumConstants = clazz.getEnumConstants();
        for (Object object : enumConstants) {
            Enum enumValue = (Enum) object;
            enumNames.add(enumValue.name());
        }

        Map<String, Object> dataMap = CollectionUtils.toMap("enumNames", enumNames);

        String templateInput = ResourceUtil.classPathResourceInputStreamToString("api-doc-template/enum_structure.htm");
        this.renderPage(templateInput, dataMap, request, response);
    }

    private void renderTypeStructurePage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String type = request.getParameter("type");
        Class clazz = ReflectUtil.classForName(type);

        Map<String, Object> dataMap = EntityStructureUtil.typeStructure(clazz);

        String templateInput = ResourceUtil.classPathResourceInputStreamToString("api-doc-template/type_structure.htm");
        this.renderPage(templateInput, dataMap, request, response);
    }
}